﻿using Afterbunny.Windows.Helpers;
using DistributedVisionRunner.Module;
using System;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Forms;

namespace DistributedVisionRunner.App.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            SetMinimizeToTray(this
                );
        }

        private void MainWindow_OnClosed(object sender, EventArgs e)
        {
            FileSystemHelper.RemoveOutdatedFiles(Constants.AppDataDir, TimeSpan.FromDays(30), "log");
        }

        /// <summary>
        /// A <see cref="NotifyIcon"/> will be shown in the tray bar if minimized
        /// </summary>
        /// <param name="window">the window to add <see cref="NotifyIcon"/></param>
        /// <param name="iconPath">the ico file path for the <see cref="NotifyIcon"/>. If null or empty is provided the assembly icon of the given window will be used</param>
        /// <param name="contextMenuActions"></param>
        /// <param name="balloonTitle"></param>
        /// <param name="balloonText"></param>
        /// <param name="balloonTimeout"></param>
        /// <param name="appName">Name of your application. If not provided the title of the provided <see cref="window"/> will be used</param>
        /// <returns></returns>
        public static NotifyIcon SetMinimizeToTray(Window window, string iconPath = null, (string, Action)[] contextMenuActions = null,
    string balloonTitle = null, string balloonText = null, int balloonTimeout = 2, string appName = null)
        {
            var strip = new ContextMenuStrip();
            strip.Items.Add("Exit", null, (sender, args) => { window.Close(); });
            var hasExtraContextMenuActions = contextMenuActions != null && contextMenuActions.Any();
            if (hasExtraContextMenuActions)
            {
                foreach (var (title, action) in contextMenuActions)
                {
                    strip.Items.Add(title, null, (sender, args) => action.Invoke());
                }
            }


            var iconText = appName ?? window.Title;
            if (string.IsNullOrEmpty(iconText))
            {
                throw new ArgumentException("Either window.Title or appName should be specified", nameof(appName));
            }

            var balloonTipText = balloonText ?? "程序已最小化至托管栏, 双击图标可展开";

            Icon icon;
            if (string.IsNullOrEmpty(iconPath))
            {
                var exePath = Regex.Replace(window.GetType().Assembly.Location, "dll$", "exe");
                icon = System.Drawing.Icon.ExtractAssociatedIcon(exePath);
            }
            else
            {
                icon = new Icon(iconPath);
            }

            var ni = new NotifyIcon
            {
                Icon = icon,
                Visible = false,
                ContextMenuStrip = strip,
                Text = iconText,
                BalloonTipText = balloonTipText,
                BalloonTipTitle = balloonTitle ?? iconText

            };


            ni.DoubleClick +=
                (sender, args) =>
                {
                    window.Show();
                    window.WindowState = WindowState.Normal;
                };

            // Hide window and show icon if minimized
            window.StateChanged += (sender, args) =>
            {
                if (window.WindowState == WindowState.Minimized)
                {
                    ni.Visible = true;
                    ni.ShowBalloonTip(balloonTimeout);
                    window.Hide();
                }
                else
                {
                    ni.Visible = false;
                }
            };

            // Let icon disappear after app exits
            window.Dispatcher.ShutdownStarted += (sender, args) =>
            {
                ni.Icon = null;
            };

            return ni;
        }

    }
}
